<template>
  <div class="devicePreload-page">
    <div class="search-field">
      <el-form :model="searchForm" inline>
        <el-form-item label="预部署编码" prop="code">
          <el-input
            placeholder="请输入预部署编码"
            v-model="searchForm.code"
            autocomplete="off"
          />
        </el-form-item>
        <el-form-item label="选择门店" prop="storeId">
          <el-select-v2
            style="width: 240px"
            v-model="searchForm.storeId"
            placeholder="请选择门店"
            filterable
            :options="storeList"
            :props="{
              label: 'name',
              value: 'id',
            }"
          >
          </el-select-v2>
        </el-form-item>
        <el-form-item label="部署状态" prop="deployStatus">
          <el-select
            style="width: 220px"
            v-model="searchForm.deployStatus"
            placeholder="请选择部署状态"
          >
            <el-option
              v-for="option in preloadStatusOptions"
              :key="option.id"
              :label="option.name"
              :value="option.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <div>
            <el-button type="primary" @click="startSearch"> 查询 </el-button>
            <el-button @click="startClear"> 重置 </el-button>
          </div>
        </el-form-item>
      </el-form>
    </div>
    <div class="table-pagination-content">
      <div class="btns-fun-field">
        <!-- v-if="userPermission.addUserPerm" -->
        <el-button
          type="primary"
          @click.prevent="showAddEditDialog"
          :icon="Plus"
        >
          新增设备预部署
        </el-button>
      </div>
      <div class="table-field">
        <el-table
          :data="tableData"
          border
          stripe
          style="width: 100%"
          v-loading="tableLoading"
        >
          <el-table-column prop="code" label="预部署编码" width="140" />
          <el-table-column prop="storeNumber" label="门店编码" width="110" />
          <el-table-column prop="storeName" label="门店名称" width="240" />
          <el-table-column
            prop="deployStatusName"
            label="预部署状态"
            width="110"
          >
            <template #default="scoped">
              <el-tag v-if="scoped.row.deployStatus == 1" type="success"
                >已部署</el-tag
              >
              <el-tag v-else type="danger">待部署</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="生成时间" width="190" />
          <el-table-column prop="expires" label="到期时间" width="190" />
          <el-table-column prop="status" label="设备状态" width="100">
            <template #default="scope">
              <el-tag
                :type="scope.row.status == '' ? 'success' : 'danger'"
                disable-transitions
                >{{ scope.row.status == 0 ? '启用' : '关闭' }}</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" width="190" />

          <el-table-column prop="updateTime" label="更新时间" width="190" />
          <el-table-column label="操作" min-width="260px" fixed="right">
            <template #default="scope">
              <el-button
                type="primary"
                size="small"
                @click.prevent="showFinishDialog(scope.row, 2)"
                >部署完成确认</el-button
              >
              <!-- v-if="rolePermission.editRolePerm" -->
              <!-- <el-button
                type="success"
                size="small"
                @click.prevent="showAddEditDialog(scope.row, 2)"
                >编辑</el-button
              > -->
              <!-- v-if="rolePermission.removeRolePerm" -->
              <el-button
                type="danger"
                size="small"
                @click.prevent="showRemoveDialog(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="pagination-field">
        <el-pagination
          v-model:current-page="formData.pageIndex"
          v-model:page-size="formData.pageSize"
          :page-sizes="[10, 20, 30, 40]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="formData.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <DevicePreloadAdd v-model="addUpdateRef"></DevicePreloadAdd>
    <DevicePreloadRemove v-model="removeRef"></DevicePreloadRemove>
    <DevicePreloadFinish v-model="finishRef"></DevicePreloadFinish>
  </div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import {
  getDevicePreloadPagination,
  getDevicePreloadAllList,
} from '@/api/dms-device-preload.api'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
// import { useUserPermission } from "@/utils/permission.utils";
import DevicePreloadRemove from './DevicePreloadRemove.vue'
import DevicePreloadAdd from './DevicePreloadAdd.vue'
import DevicePreloadFinish from './DevicePreloadFinish.vue'
import { getCanUseCode } from '@/api/fms-code-dict.api'
import { getStorePagination, getStoreAllList } from '@/api/tms-store.api'
import { preloadStatusOptions } from '@/utils/common.utils'

const titleName = `设备预部署`
// const userPermission = useUserPermission();

/****
 * =============== 新增、修改相关操作 =====================
 */
const addUpdateRef = reactive({
  visible: false,
  disabled: false,
  title: `设备预部署`,
  curSelectRow: {},
  storeList: [],
  form: {},
  rules: {},
  refreshDataList: () => {
    getDataList()
  },
})

// const requestCanUseCode = () => {
// 	getCanUseCode({ type: 8 })
// 			.then((res: any) => {
// 				console.log('getCanUseCode: ', res)
// 				addUpdateRef.form.number = res
// 			})
// 			.catch((err) => {
// 				ElMessage.error(err.msg)
// 			})
// }

const showAddEditDialog = (item: any, type: number) => {
  //新增
  if (item.target) {
    let form = {
      id: null,
      code: '',
      storeNumber: '',
      storeName: '',
      status: '',
      deployStatus: '',
      remark: '',
      expires: '',
      disabled: false,
    }
    addUpdateRef.visible = true
    addUpdateRef.disabled = false
    addUpdateRef.form = form
    // requestCanUseCode()
    return
  }

  let form = {
    id: item.id,
    code: item.code,
    storeNumber: item.storeNumber,
    storeName: item.storeName,
    status: item.status,
    deployStatus: item.deployStatus,
    remark: item.remark,
    expires: item.expires,
    disabled: false,
  }
  addUpdateRef.visible = true
  addUpdateRef.disabled = true
  addUpdateRef.form = form
}

const finishRef = reactive({
  visible: false,
  title: `部署完成确认`,
  curSelectRow: {},
  form: {},
  deviceList: [],
  refreshDataList: () => {
    getDataList()
  },
})

const showFinishDialog = (item: any) => {
  finishRef.visible = true
  finishRef.curSelectRow = item
  finishRef.form = item
  let deviceIds = item.deviceIds || '[]'
  let deviceList = JSON.parse(deviceIds)
  finishRef.deviceList = deviceList
  // deviceList
}

/****
 * =============== 删除操作 =====================
 */
const removeRef = reactive({
  visible: false,
  title: `设备预部署`,
  curSelectRow: {},
  refreshDataList: () => {
    getDataList()
  },
})
const showRemoveDialog = (item: any) => {
  removeRef.visible = true
  removeRef.curSelectRow = item
}

/****
 * =============== 搜索、表格、分页 =====================
 */
const formData = reactive({
  pageIndex: 1,
  pageSize: 10,
  total: 0,
})

const searchForm = ref({
  code: '',
  storeId: '',
  storeNumber: '',
  storeName: '',
  status: '',
  deployStatus: '',
  remark: '',
  expires: '',
})

const tableLoading = ref(false)
const tableData = ref([])
/***
 * 开始搜索
 */
const startSearch = () => {
  formData.pageIndex = 1
  getDataList()
}

/***
 * 重置搜索条件
 */
const startClear = () => {
  formData.pageIndex = 1
  let value = searchForm.value
  Object.keys(value).forEach((key) => {
    ;(value as any)[key] = ''
  })
  getDataList()
}

const handleSizeChange = (value: number) => {
  formData.pageSize = value
  getDataList()
}

const handleCurrentChange = (value: number) => {
  formData.pageIndex = value
  getDataList()
}

const getDataList = () => {
  let searchCondition: any = {}

  let code = searchForm.value.code
  if (code) {
    searchCondition.code = code
  }
  let storeId = searchForm.value.storeId
  if (storeId) {
    searchCondition.storeId = storeId
  }

  let deployStatus = searchForm.value.deployStatus
  if (deployStatus) {
    searchCondition.deployStatus = deployStatus
  }

  tableLoading.value = true
  getDevicePreloadPagination({
    pageSize: formData.pageSize,
    pageIndex: formData.pageIndex,
    ...searchCondition,
  })
    .then(function (res: any) {
      // preloadStatusOptions

      tableLoading.value = false
      let list = res.list || []
      list = list.forEach((item: any) => {
        let findItem = preloadStatusOptions.find((row) => {
          return row.id == item.deployStatus
        })
        if (findItem) {
          item.deployStatusName = findItem.name
        } else {
          item.deployStatusName = ''
        }

        item.statusName = preloadStatusOptions[item.status]
        return item
      })

      tableData.value = res.list || []
      formData.total = Number(res.total)
    })
    .catch((error) => {
      console.log(error)
      tableLoading.value = false
    })
}

const storeList = ref([])
const requestStoreList = () => {
  getStoreAllList({})
    .then((res: any) => {
      storeList.value = res || []
      addUpdateRef.storeList = storeList.value
    })
    .catch((err) => {
      ElMessage.error(err.msg)
    })
}

onMounted(() => {
  requestStoreList()
  getDataList()
})
</script>
<style lang="scss" scoped>
.devicePreload-page {
  height: 100%;
}

.btns-fun-field {
  margin-bottom: 20px;
}

.pagination-field {
  display: flex;
  justify-content: flex-end;
  margin: 20px 0;
}

.btn-inner {
  display: flex;
  justify-content: center;
  color: #fff;
}

.tag-field {
  .el-tag {
    margin-right: 5px;
    &:last-child {
      margin-right: 0;
    }
  }
}

.search-field {
  margin-bottom: 12px;
  background: #fff;
  padding: 20px 20px 0px 20px;
  border-radius: 8px;
}

.devicePreload-page-content {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
}
</style>
